package com.i72.basic.context;

import org.apache.commons.collections.map.AbstractReferenceMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 线程上下文变量存储
 */
public class ThreadContext {




    private final static Map<String,Map<String,Object>> MAP = new HashMap<>();
    private final static Map<String,Map<String, List<Object>>> MAP_LIST = new HashMap<>();

    public static void set(String key,Object value){

        String threadName = getThreadName();

        if(!MAP.containsKey(threadName)){
            MAP.put(threadName,new HashMap<>());
        }
        Map data = MAP.get(threadName);

        data.put(key,value);
    }

    public static void add(String key,Object value){
        String threadName = getThreadName();

        if(!MAP_LIST.containsKey(threadName)){
            Map map = new HashMap();
            map.put(key,new ArrayList<>());
            MAP_LIST.put(threadName,map);
        }
        List<Object> list = MAP_LIST.get(threadName).get(key);
        list.add(value);

    }

    private static String getThreadName(){
        return Thread.currentThread().getName();
    }

    public static void destory(String key){
        String name = getThreadName();
        if(MAP.containsKey(name)){
            MAP.get(name).remove(key);
        }
    }

    public static void destory(){
        String name = getThreadName();
        if(MAP.containsKey(name)){
            MAP.remove(name);
        }
    }

    public static Object get(String key){
        String name = getThreadName();
        if(MAP.containsKey(name)){
            return MAP.get(name).get(key);
        }
        return null;
    }

    public static List<Object> getList(String key) {
        String name = getThreadName();
        if (MAP_LIST.containsKey(name)) {
            return MAP_LIST.get(name).get(key);
        }
        return null;
    }

}
